package com.codeTop;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: shaki
 * @Date: 2021/8/18 14:56
 */
public class K个一组翻转链表 {
    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5};
        int k = 3;
        ListNode head = createListNode(nums);
        print(head);
        head = reverseListNode(head, k);
        print(head);
    }
    public static ListNode reverseListNode(ListNode head, int k){
        ListNode ans = new ListNode(-1);
        ans.next = head;
        ListNode pre = ans;
        while (head != null){
            ListNode tail = pre;
            for (int i = 0; i < k; i++) {
                tail = tail.next;
                if (tail == null) {
                    return ans.next;
                }
            }
            ListNode next = tail.next;
            ListNode[] temp = reverseNode(head,tail);
            head = temp[0];
            tail = temp[1];
            pre.next = head;
            tail.next = next;
            pre = tail;
            head = next;
        }
        return ans.next;
    }

    private static ListNode[] reverseNode(ListNode head, ListNode tail) {
        ListNode pre = null;
        ListNode cur = head;
        while(tail != pre){
            ListNode p = cur.next;
            cur.next = pre;
            pre = cur;
            cur = p;
        }
        return new ListNode[]{tail,head};
    }

    public static ListNode createListNode(int[] nums){
        ListNode head = new ListNode(-1);
        ListNode p = head;
        for (int i = 0; i < nums.length; i++) {
            p.next = new ListNode(nums[i]);
            p = p.next;
        }
        return head.next;
    }
    public static void print(ListNode head){
        List<Integer> ans = new ArrayList<>();
        while (head != null){
            ans.add(head.value);
            head = head.next;
        }
        System.out.println(ans.toString());
    }
    static class ListNode{
        int value;
        ListNode next;
        public ListNode(int value) {
            this.value = value;
        }
    }
}
